<?php
//author: weibo.com/10coder	
require_once(dirname(__FILE__) . '/../../common/api3.class.php');

//apns基础类
class api3_apns_base extends api3_base {
	private static $inst;
	private $user;
	private $password;
	private static $base_url  = 'http://127.0.0.1:8010/';
	
	public function __construct() {
		parent::__construct(__CLASS__);
		$this->load_http();
	}
	
	public static function instance() {
                if(self::$inst == null) self::$inst = new api3_apns_base();
                return self::$inst;
        }
	
	public function auth($user, $password) {
		$this->user = $user;
		$this->password = $password;
		return $this;
	}
	
	private function request(&$post, $url) {
		$json = http_request($url, $post, '', $errno);
                if($errno) {
                        $this->seterrno(API3_ERR_HTTP, $errno);
                }
                else {
                        $json = json_decode($json);
                        if(isset($json->status_code) && $json->status_code != 0) {
                        $this->seterrno(API3_ERR_APNS_TOKEN, $json->status_code);
                        }
                }
		return $this;
	}
	
	private function token_base($uid, $token, $uri) {
		$post = array(
			'app_key' => $this->user,
			'app_secret' => $this->password,
			'uid' => $uid,
			'devicetoken' => $token,
			'plat' => 'iphone',
		);
		$url = self::$base_url . $uri;
		return $this->request($post, $url);
	
	}

	public function token($uid, $token) {
		return $this->token_base($uid, $token, 'api_token/regist');
	}

	public function untoken($uid, $token) {
		return $this->token_base($uid, $token, 'api_token/unregist');
	}
		
	public function push($uid, $msg) {
		$post = array(
                        'app_key' => $this->user,
                        'app_secret' => $this->password,
			'uid' => $uid,
			'body' => $msg,
                        'plat' => 'iphone',
                );
		$url = self::$base_url . 'api_message/push';
		return $this->request($post, $url);;
	}

		
}

